<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Http\Requests\Transport\OrderRequest;
use App\Models\airline\base\RouteModel;
use App\Models\base\AccountModel;
use App\Models\base\WarehouseModel;
use App\Models\CustomerChargeModel;
use App\Models\finance\InvoiceModel;
use App\Models\OrderModel;
use App\Models\OrderReceiveModel;
use App\Models\RecBillModel;
use App\Models\RecBillTicketModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\base\CurrencyModel;
use App\Models\base\SubjectModel;
use App\Models\CountryModel;
use App\Models\DictionaryModel;
use App\Models\TakeOrderRecModel;

//账单列表
class Recbill_old extends Controller
{
    use OrderRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = (function($request) {
            $auth = $request->get('auth');
            $sn = trim($request->input('sn', ''));
            $start_time = trim($request->input('start_time', ''));
            $end_time = trim($request->input('end_time', ''));
            $bill_status = intval($request->input('bill_status', 0));
            $currency = trim($request->input('currency', ''));
            $ticket_status = intval($request->input('ticket_status', 0));

            $query = RecBillModel::query()->where('customer_id', $auth->id);

            if($sn) { $query->where('sn', $sn); }
            if($start_time) { $query->where('created_at', '>=', $start_time); }
            if($end_time) { $query->where('created_at', '<=', $end_time); }
            if($bill_status) { $query->where('bill_status', $bill_status); }
            if($currency) { $query->where('currency', $currency); }
            if($ticket_status) { $query->where('ticket_status', $ticket_status); }

            return $query;
        })($request);

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
           
            $res = [
                'id' => $item->id,
                'sn' => $item->sn,
                'created_at' => $item->created_at->toDateTimeString(),
                'currency' => $item->currency,
                'amount' => $item->amount,
                'take_order_count' => $item->take_order_ids->count(),
                'status_name' => RecBillModel::BILL_STATUS_MAPS[$item->bill_status ?? ''] ?? '',
                'ticket_status_name' => RecBillModel::TICKET_STATUS_MAPS[$item->ticket_status ?? ''] ?? '',
                'remark' => $item->remark,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //确认收款
    public function confirm(Request $request, $id){
        $params = $request->all();
        $auth = $request->get('auth');

        $ticket = intval($params['ticket'] ?? 0);
        if($ticket == 1) {
            $validator = Validator::make($params, [
                'invoice_id' => 'required',
                'amount' => 'required|numeric|gt:0',
            ], [
                'invoice_id.required' => '请选择发票',
                'amount.required' => '请输入金额',
                'amount.gt' => '金额必须大于0'
            ]);
        
            if ($validator->fails()) {
                return $this->error($validator->errors()->first());
            }

            $invoice = InvoiceModel::where('customer_id', $auth->id)
                ->find($params['invoice_id']);
            if(!$invoice) {
                return $this->error('发票不存在');
            }

        }

        $auth = $request->get('auth');
        $bill = RecBillModel::where('customer_id', $auth->id)->find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        if($bill->bill_status != RecBillModel::BILL_WAIT_CONFIRM) {
            return $this->error('账单状态不正确');
        }

        $bill->bill_status = RecBillModel::BILL_CONFIRMED;
        $bill->invoice_id = intval($params['invoice_id'] ?? 0);
        $bill->invoice_amount = floatval($params['amount'] ?? 0);
        if($ticket == 1) {
            $bill->ticket_status = RecBillModel::TICKET_ISSUED;
        }
        $bill->confirm_at = date('Y-m-d H:i:s');
        $bill->save();

        return $this->success();
    }

    //驳回账单
    public function reject(Request $request, $id){
        $auth = $request->get('auth');
        $remark = trim($request->input('remark', ''));
        $bill = RecBillModel::where('customer_id', $auth->id)->find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        if($bill->bill_status != RecBillModel::BILL_WAIT_CONFIRM) {
            return $this->error('账单状态不正确');
        }

        $bill->bill_status = RecBillModel::BILL_REJECTED;
        $bill->reject_remark = $remark;
        $bill->reject_at = date('Y-m-d H:i:s');
        $bill->save();

        return $this->success();
    }

    //付款
    public function pay(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'amount' => 'required|numeric|gt:0',
            'attachment' => 'required',
        ], [
            'amount.required' => '请输入金额',
            'amount.gt' => '金额必须大于0',
            'attachment.required' => '请上传附件'
        ]);
    
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $bill = RecBillModel::where('customer_id', $auth->id)->find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }


        if($bill->bill_status != RecBillModel::BILL_CONFIRMED) {
            return $this->error('账单状态不正确');
        }

        $bill->bill_status = RecBillModel::BILL_PAID;
        $bill->pay_amount = $params['amount'];
        $bill->pay_attachment = $params['attachment'];
        $bill->pay_remark = trim($params['remark'] ?? '');
        $bill->pay_at = date('Y-m-d H:i:s');
        $bill->save();

        return $this->success();

    }

    //详情
    public function detail(Request $request, $id){
        $auth = $request->get('auth');
        $bill = RecBillModel::where('customer_id', $auth->id)->find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        $take_orders = TakeOrderModel::whereIn('id', $bill->take_order_ids->pluck('take_order_id'))
            ->with(['orders'])
            ->get();
        $detail = [
            'id' => $bill->id,
            'sn' => $bill->sn,
            'created_at' => $bill->created_at->toDateTimeString(),
            'take_order_count' => $bill->take_order_ids->count(),
            'currency' => $bill->currency,
            'amount' => $bill->amount,
            'status_name' => RecBillModel::BILL_STATUS_MAPS[$bill->bill_status ?? ''] ?? '',
            'ticket_status_name' => RecBillModel::TICKET_STATUS_MAPS[$bill->ticket_status ?? ''] ?? '',
            'remark' => $bill->remark,
            'create_user' => $bill->create_admin?->staff->name ?? '',
            'confirm_at' => $bill->confirm_at,
            'reject_at' => $bill->reject_at,
            'reject_remark' => $bill->reject_remark,
            'ticket' => $bill->ticket->map(function($item) {
                return [
                    'id' => $item->id,
                    'type' => RecBillTicketModel::TYPE_MAPS[$item->type],
                    'amount' => $item->amount,
                    'annex' => $item->annex,
                    'create_user' => $item->create_admin?->staff->name ?? '',
                    'created_at' => $item->created_at->toDateTimeString(),
                ];
            }),
            'take_orders' => $take_orders->map(function($take_order) use ($bill){
                $split_order_count = 0;
                foreach($take_order->orders as $order) {
                    $split_order_count += $order->split_order_addr->count();
                } 

                $routes = RouteModel::whereIn('id', $take_order->flight->items->pluck('route_id'))
                    ->pluck('name')->toArray();

                $flight_no = BaseFlightModel::whereIn('id', $take_order->flight->items->pluck('airline_flight_id'))
                    ->pluck('flight_number')->toArray();
                return [
                    'id' => $take_order->id,
                    'sn' => $take_order->sn,
                    'slipt_order_count' => $split_order_count,
                    'order_count' => $take_order->orders->count(),
                    'fee_weight' => $take_order->fee_weight,
                    'route' => implode(',', $routes),
                    'flight_no' => implode(',', $flight_no),
                    'currency' => $bill->currency,
                    'amount' => $bill->amount,
                    'take_off_time' => $take_order->flight->take_off_time ?? '',
                    'created_at' => $take_order->created_at->toDateTimeString(),
                    'settle_time' => $take_order->settle_time
                ];
            })
        ];

        return $this->success($detail);
    }

    //提单详情
    public function take_order_detail(Request $request, $id) {
        $auth = $request->get('auth');
        $take_order = TakeOrderModel::where('customer_id', $auth->id)->find($id);
        if(!$take_order) {
            return $this->error('记录不存在');
        }

        $des = CountryModel::whereIn('id', $take_order->flight->items->pluck('destination_id'))
                ->pluck('name')->toArray();

        $routes = RouteModel::whereIn('id', $take_order->flight->items->pluck('route_id'))
            ->pluck('name')->toArray();

        $flight_no = BaseFlightModel::whereIn('id', $take_order->flight->items->pluck('airline_flight_id'))
            ->pluck('flight_number')->toArray();

        $detail = [
            'id' => $take_order->id,
            'sn' => $take_order->sn,
            'des_country' => implode(',', $des),
            'order_count' => $take_order->orders->count(),
            'storage_weight' => $take_order->orders->sum('storage_weight'),
            'reality_weight' => $take_order->reality_weight,
            'route' => implode(',', $routes),
            'take_off_time' => $take_order->flight->take_off_time ?? '',
            'flight_no' => implode(',', $flight_no),
            'orders' => $take_order->orders->map(function($order) {
                $packages_name = DictionaryModel::whereIn('id', explode(',', $order->packages))
                    ->pluck('name');
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'big_pkgs' => $order->big_pkgs,
                    'pre_out_date' => $order->pre_out_date,
                    'des_country_name' => $order->airport->country_name ?? '',
                    'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
                    'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$order->clearance_mode] ?? '',
                    'is_clearance' => $order->is_clearance,
                    'pre_volume' => $order->pre_volume,
                    'storage_weight' => $order->storage_weight,
                    'packages_name' => $packages_name,
                    'storage_time' => $order->storage_time,
                ];
            })
        ];



        $items = TakeOrderRecModel::where('take_order_id', $id)->get();
        $list = $items->map(function($item) {
            $name = TakeOrderRecModel::TYPE_MAPS[$item->type] ?? '';
            if($item->type == TakeOrderRecModel::TYPE_OTHER) {
                $subject = SubjectModel::find($item->subject_id);
                $name = '补录' . ($subject->name ?? '');
            }

            return [
                'id' => $item->id,
                'name' => $name,
                'currency' => $item->currency,
                'sys_amount' => $item->sys_amount,
                'amount' => $item->amount,
                'symbol' => $item->symbol,
                'create_user' => $item->create_admin->staff->name ?? '系统生成',
                'created_at' => $item->created_at->toDateTimeString(),
                'remark' => $item->remark,
                'is_sys' => $item->is_sys
            ];
        });

        $collect = [];
        foreach($list as $item) {
            if(isset($collect[$item['symbol']])) {
                $collect[$item['symbol']] += $item['amount'];
            } else {
                $collect[$item['symbol']] = $item['amount'];
            }
        }

        $result = '';
        foreach ($collect as $symbol => $value) {
            if (!empty($result)) {
                $result .= ", ";
            }
            $result .= $symbol . $value;
        }

        $detail['rcs'] = $list;

        return $this->success($detail);
    }

    //入仓单详情
    public function order_detail(Request $request, int $id){
        $auth = $request->get('auth');
        $order = OrderModel::withCount('split_order_addr')
            ->with([
                'split_order_addr'
            ])->find($id);
        if(!$order) {
            return $this->error('记录不存在');
        }

        $take_receive = OrderReceiveModel::where('order_id', $order->id)
            ->where('type', OrderReceiveModel::TAKE_TYPE)
            ->first();

        
        $packages_name = DictionaryModel::whereIn('id', explode(',', $order->packages))
            ->pluck('name');

        $res = [
            'id' => $order->id,
            'sn' => $order->sn,
            'take_order_no' => $order->take_order->sn ?? '',
            'pre_weight' => $order->pre_weight,
            'storage_weight' => $order->storage_weight,
            'split_order_addr_count' => $order->split_order_addr_count ?? 0,
            'status' => OrderModel::STATUS_MAPS[$order->status] ?? '',
            'pre_out_date' => $order->pre_out_date,
            'is_clearance' => $order->is_clearance,
            'des_country' => $order->airport->country_name ?? '',
            'des_city' => $order->des_city->name ?? '',
            'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
            'clearance_mode' => OrderModel::CLEARANCE_MODE_MAPS[$order->clearance_mode] ?? '',
            'pre_volume' => $order->pre_volume,
            'packages' => $packages_name,
            'big_pkgs' => $order->big_pkgs,
            'small_pkgs' => $order->small_pkgs,
            'pre_time' => $order->pre_time,
            'confirm_time' => $order->confirm_time,
            'storage_time' => $order->storage_time,
            'outstock_time' => $order->outstock_time,
            'arrive_time' => $order->arrive_time,
            'signed_time' => $order->signed_time,
            'take_receive' => [
                'id' => $take_receive->id ?? '',
                'order_id' => $take_receive->order_id ?? '',
                'sn' => $take_receive->sn ?? '',
                'addr' => $take_receive->addr ?? '',
                'nums' => $order->big_pkgs ?? '',
                'goods_name' => $take_receive->goods_name ?? '',
                'weight' => $order->pre_weight ?? '',
                'remark' => $take_receive->remark ?? '',
            ],
            'split_order' => $order->split_order_addr ?? [],
        ];

        return $this->success($res);

        
        
    }

    //发票信息
    public function invoices(Request $request) {
        $auth = $request->get('auth');

        $list = InvoiceModel::where('customer_id', $auth->id)->get();

        return $this->success($list);
    }

}
